package com.atguigu.srb.serviceoss.service.impl;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.atguigu.srb.serviceoss.config.OssProperties;
import com.atguigu.srb.serviceoss.service.OssService;
import com.atguigu.srb.base.exception.SrbException;
import com.atguigu.srb.base.result.ResponseEnum;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Service
public class OssServiceImpl implements OssService {
    @Override
    public String upload(MultipartFile file, String module) {
        //获取文件的上传名称
        String fileName= file.getOriginalFilename();
        // 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。
        String objectName = module+new DateTime().toString("/yyyy/MM/dd/")
                +System.currentTimeMillis()+"_"
                + UUID.randomUUID().toString().substring(0,6)
                +fileName.substring(fileName.lastIndexOf("."));//截取文件扩展名
        System.out.println(objectName);
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(OssProperties.END_POINT,OssProperties.ACCESS_KEY_ID,OssProperties.ACCESS_KEY_SECRET);

        try {

            //获取文件上传输入流
            InputStream inputStream = file.getInputStream();

            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(OssProperties.BUCKET_NAME, objectName, inputStream);

            // 上传文件。
            PutObjectResult result = ossClient.putObject(putObjectRequest);
            //拼接上传成功得文件路径
            String imgPath = "https://"+OssProperties.BUCKET_NAME+".oss-cn-shanghai.aliyuncs.com/"+objectName;
            return imgPath;
        }catch (Exception e) {
            throw new SrbException(ResponseEnum.UPLOAD_ERROR);
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    @Override
    public void delete(String path) {
        String objectName = path.substring(("https://"+OssProperties.BUCKET_NAME+".oss-cn-shanghai.aliyuncs.com/").length());


        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(OssProperties.END_POINT,OssProperties.ACCESS_KEY_ID,OssProperties.ACCESS_KEY_SECRET);

        try {
            // 删除文件或目录。如果要删除目录，目录必须为空。
            ossClient.deleteObject(OssProperties.BUCKET_NAME, objectName);
        } catch (Exception e) {
            throw new SrbException(ResponseEnum.DELETE_FILE_ERROR);
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}
